package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import domain.Countrylanguage;
import utils.JDBCUtils;

public class CountryLanguageDAO {
	// 根据code查询城市
	public Countrylanguage findByCode(String countrycode) throws SQLException {
		// 1. 连接
		Connection conn = JDBCUtils.getConnection();
		// 2.
		String sql = "select * from language where Code=?";
		PreparedStatement stmt = conn.prepareStatement(sql);
		stmt.setString(1, countrycode);
		// 3.
		ResultSet rs = stmt.executeQuery();
		Countrylanguage c = null;

		if (rs.next()) {
			String language = rs.getString("Language");
			float percentage=rs.getFloat("Percentage");
			c = new Countrylanguage(countrycode,language,percentage);
		}

		return c;
	}

	// 查询所有
	public List<Countrylanguage> findAll() throws SQLException {
		// 1. 连接
		Connection conn = JDBCUtils.getConnection();
		// 2.
		String sql = "select * from language";
		PreparedStatement stmt = conn.prepareStatement(sql);
		// 3.
		ResultSet rs = stmt.executeQuery();
		List<Countrylanguage> list = new ArrayList<>();
		while (rs.next()) {
			String countrycode = rs.getString("CountryCode");
			String language = rs.getString("language");
			float percentage=rs.getFloat("Percentage");
			Countrylanguage c = new Countrylanguage(countrycode, language, percentage);
			list.add(c);
		}

		return list;
	}
}
